/**
 *   Ajax script 
 */


$(document).ready(function() { 
	
    // Input datepicker. Deo jQueryUI
    $(".date_picker").datepicker({ 
            changeMonth: true,
            changeYear: true}
    );
    $(".date_picker").datepicker("option", "dateFormat", "yy-mm-dd"); 
    
    /** 
     *  jQuery FILEUPLOAD
     *  
     *  Sluzi za jQuery upload slike sa mogucnoscu da se slika nakon uploada odmah prikaze na stranici
     *  U header se ukljucuje: 
        <!-- Ajax Upload -->
        <script src="<?=base_url()?>js/jQueryUpload/jquery.ui.widget.js"></script>
        <script src="<?=base_url()?>js/jQueryUpload/jquery.iframe-transport.js"></script>
        <script src="<?=base_url()?>js/jQueryUpload/jquery.fileupload.js"></script>
        
     *  HTML view:
        <!-- Dugme za file browse i upload. data-url je skript koji obradjuje upload --> 
        <input type="file" class="fileupload" data-url="<?=base_url()?>administration/ajax/upload_image/img/uploads" name="img" id="upload_img" class="ui-widget-content ui-corner-all" /> 
        
        <!-- Input polje u koje se upisuje file name uploadovane slike -->
        <input type="hidden" name="data[img]" id="img" value="" />
  
        <!-- Div za prikaz rezultata uploada -->
        <div id="upload_result" class="hide"></div> 
     
     *  'data-url' atribut u input file polju sadrzi:
     *              1. putanju do funkcije koji vrsi upload ( <?=base_url()?>administration/ajax/upload_image )
     *              2. parametre funkcije, koji definisu naziv input polja gde ce se upisati 
     *                 naziv slike (img) i 
     *                 naziv foldera gde ce biti uploadovana slika ( uploads/images/img )
     *                 u odnosu na root sajta. 
     *                 Root je definisan u config.php
     *                 $config['base_dir'] = ...
     *     
     *
     */
    $('.fileupload').fileupload({
        dataType: 'json',
        start: function(){                
            $('#wait').show(); // Prikazi wait gif
        },            
        done: function (e, data) {
            $('#wait').hide(); // Sakrij wait gif
            var html = $('#upload_result').html(); // Preuzmi sadrzaj div-a rezultata uploda

            if (data.result.status == 1){ // Ako je uspesno uradjen upload
                html += data.result.html; // rezultat HTML dodaj divu rezultata
                $('#upload_result').show().html(html); // prikazi rezultat uploada
                $('#'+data.result.field_name).val(data.result.file_name); // upisi ime file-a u input hide polje
                $( this ).attr('disabled',true); // Iskljuci browse dugme
            }
            else {// Ako dodje do greske 
                html += data.result.msg; // Preuzmi tekst greske
                $('#upload_result').show().html(html); // prikazi tekst greske u div rezultata
            }
        }
    });
    
    
    /**
	 * 	jQuery Tablesorter
	 *  class table = 'table_sorter'
	 */
    $(".table_sorter").tablesorter();
    $(".table_pager").tablesorterPager({
        container: $("#pager"), 
        size: 10, 
        positionFixed: false
    });

	
    
    $("#change_lang").change(function(){
        change_lang( $("#change_lang").val() );
    });

   
    $("#filter_submit").click(function(){
        filter_submit(); 
        $('#selected_user_id').val('');
    });
    
    $("#fake_users_filter_submit").click(function(){
        fake_users_filter_submit(); 
        $('#selected_user_id').val('');
    });
    
    $("#filter_reset").click(function(){
        //$(this).closest('form').find("input[type=text], select, textarea").val("").html("");
        $("#sb_to").html('');
      
        // All users
        $(this).closest('form').find("input[type=text], textarea").val("").html("");

    });
    
    /*
     *  Dialog user info
     */    
    $( "#dialog-user" ).dialog({
        autoOpen: false,
        height: 500,
        width: 800,
        modal: true,
        buttons: {
            "OK": function() {                
                $( this ).dialog("close");
            }
        }
    });
    
    $("#sb_from").change(function(){
        update_to_users($("#sb_from").val());
    });
      
    /*
     *  Dialog user add/edit
     */    
    $( "#dialog-user-add-edit" ).dialog({
        autoOpen: false,
        height: 450,
        width: 800,
        modal: true/*,
        
        buttons: {
            "OK": function() {  
                //save_user();
                $( "#form-user-add-edit" ).trigger('submit');
                $( this ).dialog("close");
            },
            "Cancel": function(){
              $( this ).dialog("close");
            }
        }
        // */
    });
    
    $( "#add_user" ).click( function() {
      
        // Set all fields to NULL
        $("#user_id").val('');
        $("#user_ip_address").val('');
        $("#user_state").val('');
        $("#user_username").val('');
        $("#user_status").val(0);
        $("#user_password").attr('disabled',false);
        $("#user_zip_code").val('');
        $("#user_password").val('');
        $("#user_password").attr('readonly',false);
        $("#user_gender").val('');
        $("#user_affiliate").val('');
        $("#user_email").val('');
        $("#user_look_for").val('');
        $("#user_registration_date").val('');
        $("#user_birthdate").val('');
        $("#user_user_group").val('');
        $("#user_team").val('');
        $("#user_flirt_text").val('');
        $("#add_to_spotlight").attr('disabled',true);
        // Open dialog form
        $("#dialog-user-add-edit").dialog("open");
      
    });
    
    
    $( "#edit_user" ).click( function() {
        edit_user();
    });
        
    $("#add_to_spotlight").click(
      function(){
        add_to_spotlight();
      }
    );
    
    $( "#form-user-add-edit" ).validate({
        rules: {
            // simple rule, converted to {required:true}
            'user[username]'   : "required", 
            'user[email]'      : "email", //required
            'user[birthdate]'  : "required",        
            'user[user_group]' : "required",
            'user[state]'      : "required"
        
        },
        messages:{
            'user[username]'  : "",
            'user[email]'     : "",
            'user[birthdate]' : "",         
            'user[user_group]': "",
            'user[state]'     : ""
        },
        submitHandler: function() {                                     
            save_user();
        },
        invalidHandler: function() { } 
    });
    
    
    /*
     *  Dialog mail to user
     */    
    $( "#dialog-mailto-user" ).dialog({
        autoOpen: false,
        height: 400,
        width: 600,
        modal: true /*,
        buttons: {
            "OK": function() {                
                $( this ).dialog("close");
            },
            "Cancel": function() {                
                $( this ).dialog("close");
            }
        }
        // */
    });
    
    $("#mailto_user").click(function(){
        mailto_user(); // populate dialog mail to user
    });
    
    // validate form mail to user (on dialog mail to user)
    $( "#form-mailto-user" ).validate({
        rules: {
            // simple rule, converted to {required:true}
            'mailto[subject]'   : "required", 
            'mailto[message]'   : "required"        
        },
        messages:{
            'mailto[subject]'  : "",        
            'mailto[message]'  : ""
        },
        submitHandler: function() {                                     
            send_user_mail();
        },
        invalidHandler: function() { } 
    });
    $("#newsletter_select_all").change(function() {   
        if(this.checked) {
            // Iterate each checkbox
            $('input#newsletter_selected').each(function() {
                this.checked = true;                        
            });
        }
        else{
            // Iterate each checkbox
            $('input#newsletter_selected').each(function() {
                this.checked = false;                        
            });
        }
    });
     $("#promotions_select_all").change(function() {   
        if(this.checked) {
            // Iterate each checkbox
            $('input#promotions_selected').each(function() {
                this.checked = true;                        
            });
        }
        else{
            // Iterate each checkbox
            $('input#promotions_selected').each(function() {
                this.checked = false;                        
            });
        }
    });
    
    $( "#dialog-promotion-code" ).dialog({
        autoOpen: false,
        height: 430,
        width: 600,
        modal: true /*,
        buttons: {
            "OK": function() {                
                $( this ).dialog("close");
            },
            "Cancel": function() {                
                $( this ).dialog("close");
            }
        }
        // */
    });
    
    $("#send_promotion_code").click(
        function(){
            send_promotion_code();
        }); 
    
    $("#auto_code").click(
      function(){
        
        if ( $("#auto_code").is (':checked'))
        {
          $('#mailto_promotion_code').val('');
          $('#mailto_promotion_code').attr('disabled',true);
        }  
        else
        {
          $('#mailto_promotion_code').attr('disabled',false);
        }
      }
    );
    
    $("#selected_submit").click(
        function (){
            selected_submit();
        });
    /*
     *  Dialog mail to users
     */    
    $( "#dialog-mailto-users" ).dialog({
        autoOpen: false,
        height: 340,
        width: 600,
        modal: true 
    });
   
    $("#mailto_newsletter").click(
        function(){
            send_newsletter();
        });
        
       
        
    $(".user_div").click(
        function(){
            $('.selected').removeClass('selected');  
            var $userId=$(this).find("#support_user_id").val();
            $(this).addClass('selected');
            showSupportMessages($userId); 
        });
    $("#refresh_users").click(
        function(){
            refreshUsers();
        });
    $("#refresh_messages").click(
        function(){
            var $userId=$('.selected').find("#support_user_id").val();
            showSupportMessages($userId);
        });
    $("#submit_support_message").click(
        function(){
            var $userId=$('.selected').find("#support_user_id").val();
            submit_support_message($userId);
        }
        );
    $("#update_monitor").click(function(){
        update_monitor();
    });
    // validate form mail to user (on dialog mail to user)
    //    $( "#form-mailto-users" ).validate({
    //     rules: {
    //        // simple rule, converted to {required:true}
    //        'mailto[subject]'   : "required", 
    //        'mailto[message]'   : "required"        
    //        },
    //     messages:{
    //         'mailto[subject]'  : "",        
    //         'mailto[message]'  : ""
    //        },
    //     submitHandler: function() {                                     
    //            send_newsletter();
    //        },
    //     invalidHandler: function() { } 
    //    });
  
    
    $("#select_period").change(function(){
        change_billing_period( $("#select_period").val() );
    });
    $("#monitor_filter input:radio").on ("change",
        function(){
            var f=$("#time_interval").is(":checked");
            $("#date_from").prop('disabled', ! f);
            $("#date_to").prop('disabled', ! f);
            $("#time_from").prop('disabled', ! f);
            $("#time_to").prop('disabled', ! f);
        }
    
        );
    // Moderators / teams
    
    /*
     *  Dialog user add/edit
     */    
    $( "#dialog-team" ).dialog({
        autoOpen: false,
        height: 400,
        width: 550,
        modal: true
        
    });
    
    // ADD TEAM
    $( "#add_team" ).click( function() {
      
        // Set all fields to NULL
        $("#team_id").val('');
        $("#team_name").val('');
        $("#team_description").val('');      
        // Open dialog form
        $("#dialog-team").dialog("open");
      
    });
    // EDIT TEAM
    $( "#edit_team" ).click( function() {
        edit_team();
    });
    
    $( "#form-team" ).validate({
        rules: {
            // simple rule, converted to {required:true}
            'team[name]'   : "required"        
        },
        messages:{
            'team[name]'  : ""
        },
        submitHandler: function() {                                     
            save_team();            
        },
        invalidHandler: function() { } 
    });
    
    $( "#tabs" ).tabs(
    {
        activate: function(event, ui) {
            var a=ui.newTab.find('a');
            var id=a.attr('id');
            id=id.substring(10);
            var did='div_'+id;
            var div=$("#conversation_list").find("#"+did);
            div.trigger('click');
        }
    }
   
    );
 var tabs = $( "#tabs" ).tabs();
 tabs.delegate( "span.ui-icon-close", "click", function() {
      var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
      $( "#" + panelId ).remove();
      tabs.tabs( "refresh" );
    });
$("#conversation_list").delegate(".conversation_div", "click", function()
    {
        $('.selected').removeClass('selected');
        $(this).addClass('selected');
  });
   

$("#send_mod_message").click(function (){
    var userFrom=$(".selected").find("#conversation_fake").val();
    var userTo=$(".selected").find("#conversation_user").val();
    send_mod_message(userFrom, userTo);
});


$( "#dialog-start-conversation" ).dialog({
        autoOpen: false,
        height: 550,
        width: 800,
        modal: true
    });
 
 
});


